﻿#region

using System;
using System.Collections;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;

#endregion

namespace MobilePal.Views.ButtonsView
{
  public static class ColorConverter
  {
    #region Fields

    private static Hashtable colorConstants;
    private static Hashtable systemColorConstants;

    #endregion

    #region Properties/Indexers

    private static Hashtable Colors
    {
      get
      {
        if (colorConstants == null)
        {
          if (colorConstants == null)
          {
            var hash = new Hashtable(StringComparer.OrdinalIgnoreCase);
            FillConstants(hash, typeof (Color));
            colorConstants = hash;
          }
        }
        return colorConstants;
      }
    }

    private static Hashtable SystemColors
    {
      get
      {
        if (systemColorConstants == null)
        {
          if (systemColorConstants == null)
          {
            var hash = new Hashtable(StringComparer.OrdinalIgnoreCase);
            FillConstants(hash, typeof (SystemColors));
            systemColorConstants = hash;
          }
        }

        return systemColorConstants;
      }
    }

    #endregion

    #region Methods

    private static void FillConstants(Hashtable hash, Type enumType)
    {
      MethodAttributes attributes = MethodAttributes.Static | MethodAttributes.Public;
      foreach (PropertyInfo info in enumType.GetProperties())
      {
        if (info.PropertyType == typeof (Color))
        {
          MethodInfo getMethod = info.GetGetMethod();
          if ((getMethod != null) && ((getMethod.Attributes & attributes) == attributes))
          {
            object[] index = null;
            hash[info.Name] = info.GetValue(null, index);
          }
        }
      }
    }

    public static Color ConvertFrom(string value)
    {
      Color result = Color.Empty;

        if (Colors.Contains(value))
          result = (Color)Colors[value];
        else
        if (SystemColors.Contains(value))
          result = (Color)SystemColors[value];
        else
          try
          {
            var argb = int.Parse(value, NumberStyles.HexNumber);
            result = Color.FromArgb(argb);
          }
          catch (FormatException)
          {
            MessageBox.Show("Cannot convert " + value + " to Color!");
          }

      return result;
    }

    #endregion
  }
}